/**
 * 蓝牙插件工具函数
 */

import { 
  PLATFORMS, 
  ERROR_CODES, 
  ERROR_MESSAGES,
  COMMON_BLE_SERVICES,
  DEVICE_TYPE_SERVICES,
  DEVICE_NAME_PATTERNS
} from './constants.js'

/**
 * 获取当前平台
 * @returns {string} 平台标识
 */
export function getCurrentPlatform() {
  // #ifdef H5
  return PLATFORMS.H5
  // #endif
  
  // #ifdef MP-WEIXIN
  return PLATFORMS.MP_WEIXIN
  // #endif
  
  // #ifdef MP-ALIPAY
  return PLATFORMS.MP_ALIPAY
  // #endif
  
  // #ifdef MP-BAIDU
  return PLATFORMS.MP_BAIDU
  // #endif
  
  // #ifdef MP-TOUTIAO
  return PLATFORMS.MP_TOUTIAO
  // #endif
  
  // #ifdef MP-QQ
  return PLATFORMS.MP_QQ
  // #endif
  
  // #ifdef MP-360
  return PLATFORMS.MP_360
  // #endif
  
  // #ifdef APP-PLUS
  return PLATFORMS.APP_PLUS
  // #endif
  
  return PLATFORMS.H5
}

/**
 * 检查是否为H5平台
 * @returns {boolean}
 */
export function isH5Platform() {
  return getCurrentPlatform() === PLATFORMS.H5
}

/**
 * 检查是否支持Web Bluetooth API
 * @returns {boolean}
 */
export function isWebBluetoothSupported() {
  return typeof navigator !== 'undefined' && 
         'bluetooth' in navigator && 
         typeof navigator.bluetooth.requestDevice === 'function'
}

/**
 * ArrayBuffer转十六进制字符串
 * @param {ArrayBuffer} buffer 
 * @returns {string}
 */
export function arrayBuffer2HexString(buffer) {
  const uint8Array = new Uint8Array(buffer)
  let hexString = ''
  for (let i = 0; i < uint8Array.length; i++) {
    hexString += uint8Array[i].toString(16).padStart(2, '0').toUpperCase()
  }
  return hexString
}

/**
 * 十六进制字符串转ArrayBuffer
 * @param {string} hexString 
 * @returns {ArrayBuffer}
 */
export function hexString2ArrayBuffer(hexString) {
  const length = hexString.length / 2
  const buffer = new ArrayBuffer(length)
  const uint8Array = new Uint8Array(buffer)
  
  for (let i = 0; i < length; i++) {
    uint8Array[i] = parseInt(hexString.substr(i * 2, 2), 16)
  }
  
  return buffer
}

/**
 * 字符串转ArrayBuffer
 * @param {string} str 
 * @returns {ArrayBuffer}
 */
export function string2ArrayBuffer(str) {
  const encoder = new TextEncoder()
  return encoder.encode(str).buffer
}

/**
 * ArrayBuffer转字符串
 * @param {ArrayBuffer} buffer 
 * @returns {string}
 */
export function arrayBuffer2String(buffer) {
  const decoder = new TextDecoder()
  return decoder.decode(buffer)
}

/**
 * 创建统一的错误对象
 * @param {number} errCode 错误码
 * @param {string} errMsg 错误消息
 * @returns {Object}
 */
export function createError(errCode, errMsg) {
  return {
    errCode,
    errMsg: errMsg || ERROR_MESSAGES[errCode] || 'Unknown error'
  }
}

/**
 * 创建成功响应对象
 * @param {Object} data 数据
 * @returns {Object}
 */
export function createSuccess(data = {}) {
  return {
    errCode: ERROR_CODES.OK,
    errMsg: 'ok',
    ...data
  }
}

/**
 * 格式化设备信息
 * @param {Object} device 设备对象
 * @param {string} platform 平台
 * @returns {Object}
 */
export function formatDeviceInfo(device, platform) {
  if (platform === PLATFORMS.H5) {
    return {
      deviceId: device.id,
      name: device.name || 'Unknown Device',
      RSSI: device.RSSI || 0,
      advertisData: device.advertismentData || new ArrayBuffer(0),
      localName: device.name || ''
    }
  } else {
    // 其他平台保持原始格式
    return device
  }
}

/**
 * 格式化服务信息
 * @param {Object} service 服务对象
 * @param {string} platform 平台
 * @returns {Object}
 */
export function formatServiceInfo(service, platform) {
  if (platform === PLATFORMS.H5) {
    return {
      uuid: service.uuid,
      isPrimary: service.isPrimary
    }
  } else {
    return service
  }
}

/**
 * 格式化特征值信息
 * @param {Object} characteristic 特征值对象
 * @param {string} platform 平台
 * @returns {Object}
 */
export function formatCharacteristicInfo(characteristic, platform) {
  if (platform === PLATFORMS.H5) {
    return {
      uuid: characteristic.uuid,
      properties: {
        read: characteristic.properties.read,
        write: characteristic.properties.write,
        writeWithoutResponse: characteristic.properties.writeWithoutResponse,
        notify: characteristic.properties.notify,
        indicate: characteristic.properties.indicate
      }
    }
  } else {
    return characteristic
  }
}

/**
 * 防抖函数
 * @param {Function} func 函数
 * @param {number} wait 等待时间
 * @returns {Function}
 */
export function debounce(func, wait) {
  let timeout
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout)
      func(...args)
    }
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
  }
}

/**
 * 节流函数
 * @param {Function} func 函数
 * @param {number} limit 限制时间
 * @returns {Function}
 */
export function throttle(func, limit) {
  let inThrottle
  return function() {
    const args = arguments
    const context = this
    if (!inThrottle) {
      func.apply(context, args)
      inThrottle = true
      setTimeout(() => inThrottle = false, limit)
    }
  }
}

/**
 * 生成UUID
 * @returns {string}
 */
export function generateUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0
    const v = c == 'x' ? r : (r & 0x3 | 0x8)
    return v.toString(16)
  })
}

/**
 * 深拷贝对象
 * @param {any} obj 
 * @returns {any}
 */
export function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') return obj
  if (obj instanceof Date) return new Date(obj)
  if (obj instanceof Array) return obj.map(item => deepClone(item))
  if (typeof obj === 'object') {
    const clonedObj = {}
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        clonedObj[key] = deepClone(obj[key])
      }
    }
    return clonedObj
  }
}

/**
 * 检查参数类型
 * @param {any} value 值
 * @param {string} type 期望类型
 * @param {string} name 参数名
 */
export function checkParamType(value, type, name) {
  const actualType = typeof value
  if (actualType !== type) {
    throw new Error(`Parameter '${name}' expected ${type}, but got ${actualType}`)
  }
}

/**
 * 检查必需参数
 * @param {Object} params 参数对象
 * @param {Array} requiredParams 必需参数列表
 */
export function checkRequiredParams(params, requiredParams) {
  for (const param of requiredParams) {
    if (!(param in params)) {
      throw new Error(`Required parameter '${param}' is missing`)
    }
  }
}

/**
 * 延迟执行
 * @param {number} ms 毫秒
 * @returns {Promise}
 */
export function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms))
}

/**
 * 超时Promise
 * @param {Promise} promise 
 * @param {number} timeout 超时时间
 * @returns {Promise}
 */
export function withTimeout(promise, timeout) {
  return Promise.race([
    promise,
    new Promise((_, reject) => {
      const timeoutId = setTimeout(() => {
        const timeoutError = new Error(`操作超时：${timeout}ms内未完成操作`)
        timeoutError.name = 'TimeoutError'
        timeoutError.code = ERROR_CODES.CONNECTION_TIMEOUT
        reject(timeoutError)
      }, timeout)
      
      // 清理定时器以防内存泄漏
      promise.finally(() => clearTimeout(timeoutId))
    })
  ])
}

/**
 * 检查设备是否支持BLE连接
 * @param {Object} device Web Bluetooth设备对象
 * @returns {Object} 检查结果
 */
export function checkDeviceBLECompatibility(device) {
  const result = {
    compatible: false,
    reason: '',
    deviceType: 'unknown',
    suggestions: []
  }
  
  if (!device) {
    result.reason = '设备对象无效'
    return result
  }
  
  // 检查是否有GATT支持
  if (!device.gatt) {
    result.reason = '设备不支持GATT（Generic Attribute Profile）'
    result.deviceType = 'classic-bluetooth'
    result.suggestions = [
      '该设备可能是经典蓝牙设备（如蓝牙耳机、音箱等）',
      'Web Bluetooth API只支持BLE（低功耗蓝牙）设备',
      '请尝试连接支持BLE的设备，如智能手环、传感器等'
    ]
    return result
  }
  
  // 基于设备名称进行启发式判断
  const deviceName = (device.name || '').toLowerCase()
  
  // 常见的音频设备关键词
  const audioDeviceKeywords = [
    'airpods', 'headphone', 'speaker', 'audio', 'music', 'sound',
    'beats', 'sony', 'bose', 'jbl', 'marshall', 'sennheiser',
    'earphone', 'earbuds', 'headset', 'buds'
  ]
  
  // 常见的BLE设备关键词  
  const bleDeviceKeywords = [
    'heart', 'sensor', 'fitness', 'watch', 'band', 'tracker',
    'meter', 'scale', 'thermometer', 'beacon', 'tile', 'tag'
  ]
  
  const isLikelyAudioDevice = audioDeviceKeywords.some(keyword => 
    deviceName.includes(keyword)
  )
  
  const isLikelyBLEDevice = bleDeviceKeywords.some(keyword => 
    deviceName.includes(keyword)
  )
  
  if (isLikelyAudioDevice) {
    result.deviceType = 'audio-device'
    result.reason = '检测到音频设备，大多数音频设备使用经典蓝牙协议'
    result.suggestions = [
      '音频设备（耳机、音箱等）通常使用经典蓝牙，不支持BLE连接',
      '如果确实需要连接音频设备，请确认设备支持BLE功能',
      '考虑使用支持BLE的智能设备替代'
    ]
  } else if (isLikelyBLEDevice) {
    result.compatible = true
    result.deviceType = 'ble-device'
    result.reason = '设备疑似支持BLE连接'
  } else {
    result.compatible = true
    result.deviceType = 'unknown-ble'
    result.reason = '设备支持GATT，应该可以尝试BLE连接'
    result.suggestions = [
      '设备类型未知，但支持GATT协议',
      '如果连接失败，请确认设备确实支持BLE功能'
    ]
  }
  
  return result
}

/**
 * 分析连接错误并提供建议
 * @param {Error} error 连接错误对象
 * @param {Object} device 设备对象
 * @returns {Object} 错误分析结果
 */
export function analyzeConnectionError(error, device) {
  const analysis = {
    errorType: 'unknown',
    userFriendlyMessage: '',
    technicalDetails: error.message || 'Unknown error',
    suggestions: [],
    isRecoverable: true
  }
  
  if (error.message && error.message.includes('Unsupported device')) {
    analysis.errorType = 'unsupported-device'
    analysis.isRecoverable = false
    
    const compatCheck = checkDeviceBLECompatibility(device)
    
    if (compatCheck.deviceType === 'audio-device' || compatCheck.deviceType === 'classic-bluetooth') {
      analysis.userFriendlyMessage = '设备不兼容：此设备不支持BLE连接'
      analysis.suggestions = [
        '该设备可能是蓝牙耳机、音箱等音频设备',
        'Web Bluetooth API不支持经典蓝牙设备',
        '请尝试连接支持BLE的设备：',
        '  • 智能手环、手表',
        '  • 健康传感器（心率计、温度计等）',
        '  • 智能家居设备',
        '  • BLE信标设备',
        '',
        '如果确需连接音频设备，请考虑：',
        '  • 使用原生App平台（非H5）',
        '  • 寻找支持BLE的音频设备'
      ]
    } else {
      analysis.userFriendlyMessage = '设备连接不支持：设备可能不兼容当前连接方式'
      analysis.suggestions = [
        '设备不支持当前的连接协议',
        '请确认设备支持BLE（低功耗蓝牙）功能',
        '尝试重新选择设备或联系设备制造商确认BLE支持'
      ]
    }
  }
  
  return analysis
}

/**
 * 根据设备名称推测设备类型
 * @param {string} deviceName 设备名称
 * @returns {string} 推测的设备类型
 */
export function guessDeviceType(deviceName = '') {
  const nameLower = deviceName.toLowerCase()
  
  for (const [deviceType, patterns] of Object.entries(DEVICE_NAME_PATTERNS)) {
    if (patterns.some(pattern => nameLower.includes(pattern))) {
      return deviceType
    }
  }
  
  return 'generic'
}

/**
 * 根据设备类型获取推荐的服务UUID列表
 * @param {string} deviceType 设备类型
 * @returns {Array} 服务UUID数组
 */
export function getRecommendedServices(deviceType) {
  const serviceNames = DEVICE_TYPE_SERVICES[deviceType] || DEVICE_TYPE_SERVICES.generic
  
  return serviceNames.map(serviceName => {
    return COMMON_BLE_SERVICES[serviceName] || serviceName
  })
}

/**
 * 根据设备名称智能获取推荐服务
 * @param {string} deviceName 设备名称
 * @returns {Array} 推荐的服务UUID数组
 */
export function getSmartRecommendedServices(deviceName = '') {
  const deviceType = guessDeviceType(deviceName)
  return getRecommendedServices(deviceType)
}

/**
 * 获取扩展的通用服务列表（包含最常用的服务）
 * @returns {Array} 通用服务UUID数组
 */
export function getCommonServices() {
  return [
    COMMON_BLE_SERVICES.generic_access,
    COMMON_BLE_SERVICES.generic_attribute,
    COMMON_BLE_SERVICES.battery_service,
    COMMON_BLE_SERVICES.device_information,
    COMMON_BLE_SERVICES.heart_rate,
    COMMON_BLE_SERVICES.nordic_uart,
    COMMON_BLE_SERVICES.esp32_uart,
    COMMON_BLE_SERVICES.xiaomi_miband
  ]
}

/**
 * 解析服务名称为UUID
 * @param {string|Array} services 服务名称或UUID数组
 * @returns {Array} UUID数组
 */
export function parseServicesToUUIDs(services) {
  if (!Array.isArray(services)) {
    services = [services]
  }
  
  return services.map(service => {
    // 如果已经是UUID格式，直接返回
    if (typeof service === 'string' && service.includes('-')) {
      return service
    }
    
    // 如果是预定义的服务名称，转换为UUID
    return COMMON_BLE_SERVICES[service] || service
  })
}

/**
 * 创建智能设备请求选项
 * @param {Object} options 用户选项
 * @returns {Object} 处理后的请求选项
 */
export function createSmartDeviceRequestOptions(options = {}) {
  const result = { ...options }
  
  // 如果用户没有指定optionalServices，尝试智能推测
  if (!result.optionalServices || result.optionalServices.length === 0) {
    // 如果有filters且包含services，使用filters中的服务
    if (result.filters && Array.isArray(result.filters)) {
      const servicesFromFilters = []
      result.filters.forEach(filter => {
        if (filter.services) {
          servicesFromFilters.push(...filter.services)
        }
      })
      
      if (servicesFromFilters.length > 0) {
        result.optionalServices = [...new Set([
          ...servicesFromFilters,
          ...getCommonServices()
        ])]
      }
    }
    
    // 如果还是没有服务，使用通用服务列表
    if (!result.optionalServices || result.optionalServices.length === 0) {
      result.optionalServices = getCommonServices()
    }
  }
  
  // 确保optionalServices都是有效的UUID
  if (result.optionalServices) {
    result.optionalServices = parseServicesToUUIDs(result.optionalServices)
    // 去重
    result.optionalServices = [...new Set(result.optionalServices)]
  }
  
  return result
}

/**
 * 为指定设备名称创建最优请求选项
 * @param {string} deviceName 设备名称（可选）
 * @param {Object} userOptions 用户自定义选项
 * @returns {Object} 优化的请求选项
 */
export function createOptimalRequestOptions(deviceName = '', userOptions = {}) {
  const smartServices = getSmartRecommendedServices(deviceName)
  const commonServices = getCommonServices()
  
  // 合并智能推荐服务和通用服务
  const allServices = [...new Set([...smartServices, ...commonServices])]
  
  const options = {
    acceptAllDevices: true,
    optionalServices: allServices,
    ...userOptions
  }
  
  // 如果用户提供了filters且没有acceptAllDevices，则删除acceptAllDevices
  if (userOptions.filters && userOptions.acceptAllDevices === undefined) {
    delete options.acceptAllDevices
  }
  
  return options
}
